package com.hw.dagl.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hw.dagl.model.Sys_Menu;
import com.hw.dagl.model.Sys_User;
import com.hw.dagl.service.MenuService;
import com.hw.dagl.service.RoleService;
import com.hw.dagl.service.UserService;
import com.hw.dao.utils.ControllerUtil;
import com.hw.utils.EncryptUtil;
import com.hw.utils.IpUtil;
import com.hw.utils.StringUtils;


@Controller
public class LoginController extends BaseController{
	@Resource
	private UserService userServiceImpl;
	@Resource
	private MenuService menuServiceImpl;
	@Resource
	private RoleService roleServiceImpl;
	/**
	 * 系统登录
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	/*@SystemLog(Modelname="登录首页",operationType="0",operationName="登录成功")*/
	public String login(HttpServletRequest request,HttpServletResponse response,Sys_User yhxx,Model model){
	    String yhmm=yhxx.getMm();
        String yzPswJiami="";
        if(null!=yhmm){
            yzPswJiami=EncryptUtil.encrypt(yhmm.trim(),"MD5");
            yhxx = userServiceImpl.findUserByYhdh(yhxx);
        }else{
            yhxx=null;
        }
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date rq=new Date();
		try {
			rq=sdf.parse(sdf.format(rq));
		} catch (ParseException e) {
			// TODO 自动生成�?catch �?
			e.printStackTrace();
		}
		Calendar bigNow = Calendar.getInstance();
		bigNow.add(Calendar.YEAR,100);//日期�?00�?
		Date bigRq=bigNow.getTime();
		int f=0;
		if(yhxx != null){//日期为空，不限制有效�?
			if(yhxx.getZhyxq()==null)
				yhxx.setZhyxq(bigRq);
			if(yhxx.getMmyxq()==null)
				yhxx.setMmyxq(bigRq);
			if(yhxx.getJsyxq()==null)
				yhxx.setJsyxq(bigRq);
		}
		if(yhxx == null){
			request.setAttribute("data", "用户名不存在!!");
			try {
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			} catch (ServletException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}else if(!yhxx.getMm().equals(yzPswJiami)){
			//request.setAttribute("data", "用户名或者密码错误！");
		}else if(!yhxx.getZt().equals("1")){
			request.setAttribute("data", "用户被锁定或停用！");
		}else if(rq.after(yhxx.getZhyxq())){
			request.setAttribute("data", "用户名已过期！");
		}else if(rq.after(yhxx.getMmyxq())){
			request.setAttribute("data", "密码已过期！");
		}else if(!IpUtil.ipIsValid(yhxx.getIpks(), yhxx.getIpjs())){//判断IP地址是否在规定范围内
			request.setAttribute("data", "用户登录所用IP超出规定范围！");
		}else if(rq.after(yhxx.getJsyxq())){
			request.setAttribute("data", "用户角色已过期！");
		}else if(StringUtils.isNotEmpty(yhxx.getIpks_r())){
			if(!IpUtil.ipIsValid(yhxx.getIpks_r(), yhxx.getIpjs_r())){
				request.setAttribute("data", "角色所用IP超出规定范围！");
			}
			f=1;
		}else{
			f=1;
		}
		if(f==0){
			request.setAttribute("data", "用户名或者密码错误！");
			try {
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		List<Sys_Menu> list = new ArrayList<Sys_Menu>();
		list = menuServiceImpl.findRoleMenuByRid(yhxx.getRid(),true);
		request.getSession().setAttribute("role", roleServiceImpl.findRoleByRid(yhxx.getRid()));
		request.getSession().setAttribute("user", yhxx);
		model.addAttribute("menuList", list);
		userServiceImpl.updateUserLogin(yhxx.getYhdh(),request);//保存用户的登录IP和登录时间
		return "index";
		
	}
	
	/**
	 * GET方式请求登录，将跳转至登录界面
	 * @param request
	 * @param response
	 */
	@RequestMapping(method=RequestMethod.GET)
	public void login(HttpServletRequest request,HttpServletResponse response){
		try {
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 移除session里面的session
	 */
	@RequestMapping(method=RequestMethod.POST)
	public void removeSession(HttpSession session,HttpServletRequest request,HttpServletResponse response){
		//Sys_User user = (Sys_User) request.getSession().getAttribute("user");
		session.removeAttribute("user");
		ControllerUtil.renderJson(response, "OK", "encoding:UTF-8", "no-cache:false");
	}
	
}
